#
# map.py
#
# File created by moptan
"""
Tool for building 2d maps

@version: 0.6.0

@author: moptan
"""

import sys, os, pygame

from pygame.locals import *
import pygame.rect

import pickle
import random
import string

from src.tile import Tile
from src.tileselectorgrid import TileSelectorGrid
from src.paintgrid import PaintGrid
from src.fileload import FileLoad
from src.filesave import FileSave
from src.inputmanager import InputManager

try:
	import Tkinter as tk
	import tkFileDialog
except:
	print ("Failed to import Tkinter")

class map_maker():
	def __init__(self):
		pygame.init()
		self.window = pygame.display.set_mode((800, 600), RESIZABLE)
		pygame.display.set_caption('Map Maker - V0.6.0')
		self.screen = pygame.display.get_surface()
		
		self._tileSelectorGrid = TileSelectorGrid(self.window.get_height())
		self._paintGrid = PaintGrid(self.window.get_height(), self.window.get_width(), self._tileSelectorGrid.width)
		
		self.rect_x = 32
		self.rect_y = 32
		
		self.mouseX = 0
		self.mouseY = 0
		self.paintX = 0
		self.paintY = 0
		
		self.cut_surface = None
		
		self.ctrl_pressed = False
		self.alt_pressed = False
		self.on_left = False
		self.on_right = False
		
		try:
			tk_root = tk.Tk()
			tk_root.withdraw()
		except:
			print ("Failed to initiate Tkinter")

		self._tileSelectorGrid.surface_setup(self.window.get_height())
		self._paintGrid.surface_setup(self.window.get_height(), self.window.get_width(), self._tileSelectorGrid.width)
		self._inputmanager = InputManager()
		
		self.game()
		
	#***********************************#
	#		Functions - Events\Other    #
	#***********************************#
		
	def bound_drawer(self):
		pygame.mouse.get_rel()
		pygame.mouse.get_rel()
		movex = 0
		movey = 0
		self.mouse_checker()
		left = self.mouseX
		top = self.mouseY
		while pygame.mouse.get_pressed()[0] == True:
			self.draw()
			pygame.event.poll()
			mouse_moveX, mouse_moveY = pygame.mouse.get_rel()
			if self.on_right:
				movex = movex + mouse_moveX
				movey = movey + mouse_moveY
				temp_rect = pygame.Rect(left, top, movex, movey)
				self._paintGrid.draw_one_rect(temp_rect)
				self.refresh_screen()
		
		self._paintGrid.boundArray.append(temp_rect)
		temp = []
		if pygame.mouse.get_pressed()[2] == True:
			self.mouse_checker()
			if self.on_right:
				for rect in self._paintGrid.boundArray:
					if rect.collidepoint(self.mouseX, self.mouseY) == True:
						temp.append(rect)
				
				if len(temp) > 1:
					save_left_min = 999999999
					save_top_min = 999999999
					save_width_min = 999999999
					save_height_min = 999999999
		
					for rect in temp:
						if rect.left - self.mouseX < save_left_min:
							save_left_min = rect.left
						if rect.top - self.mouseY < save_top_min:
							save_top_min = rect.top
						if rect.width - self.mouseX < save_width_min:
							save_width_min = rect.width
						if rect.height - self.mouseY < save_height_min:
							save_height_min = rect.height
							
					self._paintGrid.boundArray.remove(pygame.Rect(save_left_min, save_top_min, save_width_min, save_height_min))
					
				elif len(temp) == 1:
					self._paintGrid.boundArray.remove(temp[0])
				
				
	def mouse_listener(self):
		self.mouse_checker()
		fail_Safe = random.random()
		
		if self.on_left:
			pygame.mouse.get_rel()
			pygame.mouse.get_rel()
			movex = 0
			movey = 0
			left = self.mouseX
			top = self.mouseY
			for tiles in self._tileSelectorGrid.tileArray:
				tiles.set_selected(False)
			while pygame.mouse.get_pressed()[0]:
				self.mouse_checker()
				self.draw()
				pygame.event.poll()
				mouse_moveX, mouse_moveY = pygame.mouse.get_rel()
				if self.on_left:
					movex = movex + mouse_moveX
					movey = movey + mouse_moveY
					temp_rect = pygame.Rect(left, top, movex, movey)
					self._tileSelectorGrid.draw_one_rect(temp_rect)
					self.refresh_screen()
				for rect in self._tileSelectorGrid.tileArray:
					if rect.get_rect().collidepoint(self.mouseX, self.mouseY):
					#print rect.get_rect()
					   rect.set_selected(True)
			return 
					
		if self.on_right:
			while pygame.mouse.get_pressed()[0] or pygame.mouse.get_pressed()[2]:
				self.mouse_checker()
				if pygame.mouse.get_pressed()[0] and self.cut_surface != None:
					found = False
					for clips in self._paintGrid.listArray:
						if clips.get_X() == self.paintX and clips.get_Y() == self.paintY:
							found = True
							clips.add_elevation
					if found == False:
						self._paintGrid.listArray.append(Tile((self.paintX, self.paintY), self.cut_surface.get_size(), self.cut_surface, None))
				elif pygame.mouse.get_pressed()[2]:
					for clips in self._paintGrid.listArray:
						if clips.get_X() == self.paintX and clips.get_Y() == self.paintY:
							if clips.remove_elevation(fail_safe) == False:
								self._paintGrid.listArray.remove(clips)
							break
				self.draw()
			return	
		
		if pygame.mouse.get_pressed()[0] == True:
			if self.on_left:
				for tiles in self._tileSelectorGrid.tileArray:
					tiles.set_selected(False)
					if tiles.get_X() == self.paintX and tiles.get_Y() == self.paintY:
						self.cut_surface = tiles.get_Surface()[0]
						tiles.set_selected(True)
						self.refresh_screen()
			self.draw()
			
		#while pygame.mouse.get_pressed()[1] == True:
		#	self.mouse_checker()
			
	def mouse_checker(self):
		pygame.event.poll()
		self.mouseX, self.mouseY = pygame.mouse.get_pos()
		#mouse is over the Rightmost tileset
		if self.mouseX > self._paintGrid.center_distance_width and self.mouseY < self._paintGrid.mainSurface.get_height():
			self.mouseX = self.mouseX - self._paintGrid.center_distance_width + self._paintGrid.xPosition
			self.mouseY = self.mouseY + self._paintGrid.yPosition
			self.on_left = False
			self.on_right = True
		#mouse is over the Leftmost tileset
		elif self.mouseX < self._tileSelectorGrid.width and self.mouseY < self._tileSelectorGrid.mainSurface.get_height():
			self.mouseX = self.mouseX + self._tileSelectorGrid.xPosition
			self.mouseY = self.mouseY + self._tileSelectorGrid.yPosition
			self.on_left = True
			self.on_right = False
		else:
			self.on_left = False
			self.on_right = False
		
		self.paintX, self.paintY = ((self.mouseX // self.rect_x) * self.rect_x), ((self.mouseY // self.rect_y) * self.rect_y)

	#***********************************#
	#		Functions - Loops/Other	    #
	#***********************************#
	
	def game(self):
		while True:
			self.draw()
			input_event = self._inputmanager.process(pygame)
			self.mouse_checker()
			
			if input_event[type] == 'left_tile':
				if input_event[input][0] == 'Y':
					self._tileSelectorGrid.surface_moveY(input_event[input][1]*self.rect_y)
				elif input_event[input][0] == 'X':
					self._tileSelectorGrid.surface_moveX(input_event[input][1]*self.rect_x)
					
			elif input_event[type] == 'right_tile':
				if input_event[input][0] == 'Y':
					self._paintGrid.surface_moveY(input_event[input][1]*self.rect_y)
				elif input_event[input][0] == 'X':
					self._paintGrid.surface_moveX(input_event[input][1]*self.rect_x)
					
			elif input_event[type] == 'mouse_down':
				if input_event['button'] == 'click':
					if input_event['pressed']:
						self.bound_drawer()
					else:
						self.mouse_listener()
				elif input_event['button'] == 'scroll':
					if self.on_left == True:
						if input_event[input][0] == 'Y':
							self._tileSelectorGrid.surface_moveY(input_event[input][1]*self.rect_y)
						elif input_event[input][0] == 'X':
							self._tileSelectorGrid.surface_moveX(input_event[input][1]*self.rect_x)
					elif self.on_right == True:
						if input_event[input][0] == 'Y':
							self._paintGrid.surface_moveY(input_event[input][1]*self.rect_y)
						elif input_event[input][0] == 'X':
							self._paintGrid.surface_moveX(input_event[input][1]*self.rect_x)
					
			elif input_event[type] == 'file':
				if input_event[input] == 'save':
					FileSave(self, self._paintGrid.boundArray, self._paintGrid.listArray)
				elif input_event[input] == 'load':
					loaded = FileLoad()
					loaded_file = loaded.load()
					if isinstance(loaded_file, pygame.Surface):
						self._tileSelectorGrid.tileset = loaded_file
						self._tileSelectorGrid.xPosition = 0
						self._tileSelectorGrid.yPosition = 0
						self._tileSelectorGrid.surface_setup(self.window.get_height())
					else:
						self._paintGrid.boundArray, self._paintGrid.listArray = loaded_file 
						self._paintGrid.xPosition = 0
						self._paintGrid.yPosition = 0
			elif input_event[type] == 'resize':
				self.window = pygame.display.set_mode((input_event[input][0], input_event[input][1]), RESIZABLE)
				self.screen = pygame.display.get_surface()
				
				self._tileSelectorGrid.surface_setup(self.window.get_height())
				self._paintGrid.surface_setup(self.window.get_height(), self.window.get_width(), self._tileSelectorGrid.width)
			#self.input(pygame.event.get())
	
	def draw(self):
		self.screen.fill((0,0,0))
		
		self._tileSelectorGrid.draw(self.screen)
		self._paintGrid.draw()
		
		self.refresh_screen()
		
	def refresh_screen(self):
		self.screen.blit(self._tileSelectorGrid.mainSurface, (0, 0))
		self.screen.blit(self._paintGrid.mainSurface, (self._paintGrid.center_distance_width, 0))
		
		pygame.display.flip()

		
if __name__ == '__main__':
	map_maker()